package com.oscar.practice.shiro.biz.user;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oscar.practice.shiro.biz.shiro.PasswordBiz;
import com.oscar.practice.shiro.biz.shiro.UserRealm;
import com.oscar.practice.shiro.dao.user.UserDao;
import com.oscar.practice.shiro.model.user.UserInfo;
import com.oscar.practice.shiro.util.lang.JsonUtil;
import com.oscar.practice.shiro.util.web.ActionUtil;

/**
 * 用户管理
 *
 * @author tongyufu
 *
 */
@Service
public class UserBiz {

    @Autowired
    private UserRealm   userRealm;
    @Autowired
    private PasswordBiz passwordBiz;
    @Autowired
    private UserDao     userDao;

    @Transactional
    public String save(UserInfo userInfo, Integer[] roles) {
        if (userInfo.getId() == null) {
            passwordBiz.encryptPassword(userInfo);
            userDao.save(userInfo);
        } else {
            userDao.update(userInfo);
            userDao.deleteUserRoleByUserId(userInfo.getId());
        }
        for (Integer role : roles) {
            userDao.saveUserRole(userInfo.getId(), role);
        }
        return JsonUtil.toFormJson("操作成功", true);
    }

    @Transactional
    public String delete(Integer userId) {
        userDao.deleteUserRoleByUserId(userId);
        userDao.delete(userId);
        return JsonUtil.toFormJson("操作成功", true);
    }

    public String updatePassword(Map<String, String> params) {
        UserInfo userInfo = new UserInfo();
        UserInfo oldUser = userDao.queryByUsername(ActionUtil.getUser().getUsername());
        String oldPwd = params.get("oldPwd");

        userInfo.setUsername(ActionUtil.getUser().getUsername());
        userInfo.setPassword(params.get("newPwd"));
        userInfo.setId(oldUser.getId());
        oldPwd = passwordBiz.encryptPassword(oldPwd, oldUser.getSalt());
        if (!StringUtils.equals(oldPwd, oldUser.getPassword())) {
            return JsonUtil.toFormJson("原密码错误", true);
        }
        passwordBiz.encryptPassword(userInfo);
        userDao.updatePassword(userInfo);
        return JsonUtil.toFormJson("操作成功", true);
    }
}
